﻿using System;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using SyntaxTree.VisualStudio.Unity.Bridge;

namespace SolutionGeneratorHelper
{
    internal class UnitySolution : Solution
    {
        static UnitySolution()
        {
            InitFileHandler();
        }

        internal static void InitFileHandler()
        {
            ProjectFilesGenerator.SolutionFileGeneration += SolutionFileHandler;
            ProjectFilesGenerator.ProjectFileGeneration += ProjectFileHandler;
        }

        internal static string SolutionFileHandler(string name, string content)
        {
            if (!HasExtendProject())
                return content;

            UnitySolution us = new UnitySolution();
            us.ParseSolution(content);

            foreach (List<string> item in UnitySolutionHelper.ProjectConfig)
            {
                string filePath = item[0];
                UnityProject up = new UnityProject();
                up.ParseProjectFile(filePath);
                if (up.Valid)
                    us.InsertProject(up);
            }

            content = us.Serialize();
            return content;
        }

        internal static string ProjectFileHandler(string name, string content)
        {
            if (!HasExtendProject())
                return content;

            UnityProject sup = new UnityProject();
            sup.ParseProject(content);

            foreach (List<string> item in UnitySolutionHelper.ProjectConfig)
            {
                string projDependPath = item[0];
                for (int i = 1; i < item.Count; i++)
                {
                    string projDependName = item[i];
                    if(projDependName == sup.ProjectName.Value)
                        sup.InsertProjectFile(projDependPath);
                }
            }

            content = sup.Serialize();
            return content;
        }


        private static bool HasExtendProject()
        {
            return UnitySolutionHelper.ProjectConfig.Count > 0;
        }
    }
}
